<script setup lang="ts">
  import { ReloadOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import http from '@/store/http';
  import { Response } from '@/types';
  import { FormInstance, message } from 'ant-design-vue';
  import { onBeforeMount, ref } from 'vue';
  import FormItem from './FormItem.vue';
  import { useMenuStore } from '@/store';

  const menu = useMenuStore();

  interface Form {
    id: number;
    name: string;
    title: string;
    role: string;
    _isNew?: boolean;
  }

  onBeforeMount(() => {
    // 获取表单集合
    getFormList();
  });

  const getFormList = () => {
    http
      .request<Form[], Response<Form[]>>('/api/form', 'get')
      .then((res) => {
        formList.value = res.data;
      });
  };

  const formList = ref<Form[]>([]);

  const formForm = ref<Form>({
    id: undefined,
    name: undefined,
    title: undefined,
    role: undefined,
    _isNew: undefined,
  });

  const formModel = ref<FormInstance>();
  const showModal = ref(false);
  const formLoading = ref(false);

  const submit = () => {
    formLoading.value = true;
    formModel.value
      ?.validateFields()
      .then((resForm: Form) => {
        http
          .request<String, Response<String>>('/api/form', formForm.value._isNew ? 'post_json' : 'put_json', formForm.value)
          .then((res: Response<String>) => {
            if (res.code !== 200) {
              message.error(res.msg);
              return;
            }
            message.success(res.msg);
            getFormList();
            menu.getMenuList();
            showModal.value = false;
          });
      })
      .catch((e) => {
        console.error(e);
      })
      .finally(() => {
        formLoading.value = false;
      });
  };

  const cancel = () => {
    showModal.value = false;
    reset();
  };

  const reset = () => {
    formForm.value = {
      id: undefined,
      name: undefined,
      title: undefined,
      role: undefined,
      _isNew: undefined,
    };
  };

  const addForm = () => {
    formForm.value._isNew = true;
    showModal.value = true;
  };

  const refresh = () => {
    getFormList();
    menu.getMenuList();
  };

  const editForm = (form: Form) => {
    Object.assign(formForm.value, form);
    formForm.value._isNew = false;
    showModal.value = true;
  };

  const deleteForm = (form: Form) => {
    http.request<String, Response<String>>('/api/form/' + form.id, 'delete')
      .then((res: Response<String>) => {
        if (res.code !== 200) {
          message.error(res.msg);
          return;
        }
        message.success(res.msg);
        getFormList();
        menu.getMenuList();
      }).catch(e => {
      console.error(e);
    }).finally(() => {
      formLoading.value = false;
    });
  };

  interface Role {
    name: string;
    id: number;
    title: string;
  }

  const roleOptions = ref([]);

  http.request<Role[], Response<Role[]>>('api/role', 'get').then(res => {
    roleOptions.value = res.data.map((role) => {
      return {
        label: role.title,
        value: role.name,
      };
    });
  });
</script>
<template>
  <div class="form">
    <div class="top">
      <span class="total">全部:({{ formList.length }})</span>
      <div class="right-buttons">
        <a-button type="primary" @click="addForm">
          <template #icon>
            <PlusOutlined />
          </template>
          添加
        </a-button>
        <a-button type="primary" @click="refresh">
          <template #icon>
            <ReloadOutlined />
          </template>
          刷新
        </a-button>
      </div>
    </div>
    <div class="form-list">
      <FormItem v-for="(item, index) in formList" :key="item.id" :index="index + 1" :id="item.id" :name="item.name"
                :title="item.title" @editForm="editForm" @deleteForm="deleteForm" :role="item.role" />
    </div>
  </div>

  <a-modal :title="formForm._isNew ? '新增表单' : '编辑表单'" v-model:visible="showModal" @ok="submit" @cancel="cancel">
    <a-form ref="formModel" :model="formForm" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
      <a-form-item label="名称" required name="name">
        <a-input v-model:value="formForm.name" :disabled="!formForm._isNew" />
      </a-form-item>
      <a-form-item label="标题" required name="title">
        <a-input v-model:value="formForm.title" />
      </a-form-item>
      <a-form-item name="role" label="角色">
        <a-select
          v-model:value="formForm.role"
          :options="roleOptions"
        ></a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="less">
  .form {
    padding-inline: 50px;
    position: relative;

    .top {
      position: sticky;
      top: 0;
      height: 50px;
      z-index: 1;
      background-color: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .total {
        font-size: 25px;
      }

      .right-buttons {
        display: flex;
        gap: 20px;
      }
    }

    .form-list {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
  }
</style>
